<script lang="ts" setup>
import { reactive } from 'vue'
import { User, Lock, Message, Position, ChatRound, CreditCard, StarFilled } from '@element-plus/icons-vue'

const formInline = reactive({
    region1: '',
    region2: '',
})

const onSubmit = () => {
    console.log('submit!')
}
import { ref } from 'vue'

const currentPage = ref(1)
const pageSize = ref(5)
const username = ref('')
const nickname = ref('')
const totalpage = ref()
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false)
const dialogname = ref()
const displaydel = ref(false)



const handleSizeChange = (size) => {
    pageSize.value = size
    userData()
}
const handleCurrentChange = (current) => {
    currentPage.value = current
    userData()
}
import {
    Delete,
    Edit,
    WarningFilled
} from '@element-plus/icons-vue'

import { userlistServer } from '@/api/user.js';
import { ElMessage, FormRules } from 'element-plus';

const tableData = ref()

const reg = /^[\u4e00-\u9fa5]+$/
const reg_password = /(^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{5,20}$)/
const reg_email = /(^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/
const reg_phone = /(^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$)/
const reg_age = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/;//年龄是1-120之间有效

interface RuleForm {
    username: String,
    id: Number,
    nickname: String,
    email: String,
    ruler: Number,
    user_pic: String,
    phone: String,
    password: String,
    rePassword: String,
    sex: String,
    age: Number,
    hobby: String

}


const addData = ref<RuleForm>({
    username: '',
    id: null,
    nickname: '',
    email: '',
    ruler: null,
    user_pic: '',
    phone: '',
    password: '',
    rePassword: '',
    sex: '',
    age: null,
    hobby: ''

})

const checkrepassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== addData.value.password) {
        callback(new Error('两次密码输入不一致，请再次输入'))
    } else {
        callback()
    }
}

const piclist = ref([])


const userData = async () => {
    let params = {
        countpage: currentPage.value,
        pagenumber: pageSize.value,
        username: username.value ? username.value : null,
        nickname: nickname.value ? nickname.value : null
    }

    let result = await userlistServer(params)

    tableData.value = result.data.items
    for (let key in tableData.value) {
        piclist.value.push(tableData.value[key].userPic)
    }
    console.log(piclist.value)
    totalpage.value = result.data.total
}

userData();

const clearadddata = () => {
    addData.value = {
        username: '',
        id: null,
        nickname: '',
        email: '',
        ruler: null,
        phone: '',
        user_pic: '',
        password: '',
        rePassword: '',
        sex: '',
        age: null,
        hobby: ''
    }
}

import { registerServer, updatauserServer, deluserServer } from '@/api/user.js';
const adduser = async () => {
    dialogVisible.value = false;
    let result = await registerServer(addData.value) as any;
    ElMessage.success(result.message ? result.message : '添加成功')
    clearadddata()
    userData()
}

const updatauser = async () => {
    dialogVisible.value = false;
    console.log(addData.value)
    let result = await updatauserServer(addData.value) as any;
    ElMessage.success(result.message ? result.message : '修改成功')
    clearadddata()
    userData()
}

const deluser = async () => {
    displaydel.value = false
    let result = await deluserServer(addData.value.id) as any;
    ElMessage.success(result.message ? result.message : '删除成功')
    clearadddata()
    userData()
}

const rules = reactive<FormRules<RuleForm>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '用户名要求3到15位的非空字符串', trigger: 'blur' }
    ],

    email: [
        { required: false, message: '请输入邮箱', trigger: 'blur' },
        { pattern: reg_email, message: '名称允许汉字、字母、数字，域名只允许英文域名', trigger: 'blur' }
    ],

    phone: [
        { required: false, message: '请输入手机号', trigger: 'blur' },
        { pattern: reg_phone, message: '请输入正确的手机号', trigger: 'blur' }
    ],

    age: [
        { required: false, message: '请输入年龄', trigger: 'blur' },
        { pattern: reg_age, message: '年龄要求0到120岁', trigger: 'blur' }
    ],

    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: reg_password, message: '密码要求5到20位的数字和字母的组合', trigger: 'blur' }
    ],

    rePassword: [
        { validator: checkrepassword, trigger: 'blur' }
    ],


    nickname: [
        { required: false, message: '请输入昵称', trigger: 'blur' },
        { min: 1, max: 15, message: '昵称要求1到15位', trigger: 'blur' }
    ]
})



const showupdataDiglog = (row) => {
    dialogVisible.value = true
    dialogname.value = '修改用户信息'
    addData.value.username = row.username
    addData.value.nickname = row.nickname
    addData.value.email = row.email
    addData.value.id = row.id
    addData.value.phone = row.phone
    addData.value.ruler = row.ruler
    addData.value.age = row.age
    addData.value.sex = row.sex
    addData.value.hobby = row.hobby
    addData.value.user_pic = row.user_pic

}

const showdelDiglog = (row) => {
    displaydel.value = true
    dialogname.value = '提示'
    addData.value.id = row.id

}

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if ((rawFile.type !== 'image/jpeg')) {
        ElMessage.error('图片文件必须是JPG!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片文件大小不能超过 2MB!')
        return false
    }
    return true
}

import { useToken } from '@/stores/token.js';
const token = useToken()
const display = ref(false)
</script>


<template>

    <el-card style="max-width: 100%">
        <div class="card-header">
            <span>用户管理</span>
            <el-button type="primary" @click="dialogVisible = true, dialogname = '添加用户'">添加用户</el-button>
        </div>
        <div style="margin-top: 20px;">
            <hr>
        </div>
        <el-form :inline="true" class="form-inline">
            <el-form-item label="用户名" prop="username">
                <el-input placeholder="请输入待查找用户名" v-model="username"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input placeholder="请输入待查找用户昵称" v-model="nickname"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="userData()">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="default" @click="username = '', nickname = '', userData()">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%" table-layout='auto' >
            <el-table-column prop="id" label="id" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="sex" label="性别" />
            <el-table-column prop="age" label="年龄" />
            <el-table-column prop="hobby" label="兴趣爱好" />
            <el-table-column prop="nickname" label="昵称" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="ruler" label="角色" />
            <el-table-column label="操作" width="180">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showupdataDiglog(row)" />
                    <el-button type="danger" :icon="Delete" circle @click="showdelDiglog(row)" />
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="dialogVisible" :title="dialogname" width="500">
            <el-form ref="form" class="addauthor" :rules="rules" :model="addData">
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="addData.username"></el-input>
                </el-form-item>
                <el-form-item prop="age">
                    <el-input :prefix-icon="CreditCard" placeholder="请输入年龄" v-model="addData.age"></el-input>
                </el-form-item>
                <el-form-item prop="hobby">
                    <el-input :prefix-icon="StarFilled" placeholder="请输入兴趣爱好" v-model="addData.hobby"></el-input>
                </el-form-item>
                <el-form-item prop="password" v-if="dialogname == '添加用户'">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="addData.password"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword" v-if="dialogname == '添加用户'">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码"
                        v-model="addData.rePassword"></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input :prefix-icon="Message" type="email" placeholder="请输入邮箱"
                        v-model="addData.email"></el-input>
                </el-form-item>
                <el-form-item prop="phone">
                    <el-input :prefix-icon="Position" type="phone" placeholder="请输入手机号"
                        v-model="addData.phone"></el-input>
                </el-form-item>
                <el-form-item prop="nickname">
                    <el-input :prefix-icon="ChatRound" type="nickname" placeholder="请输入昵称"
                        v-model="addData.nickname"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="addData.sex" placeholder="请选择" clearable>
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="addData.ruler" placeholder="请选择" clearable>
                        <el-option label="普通用户" value="普通用户" />
                        <el-option label="作者" value="作者" />
                        <el-option label="管理员" value="管理员" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-upload v-if="display" class="avatar-uploader" action="http://localhost:8080/user/uploadimg"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                        :headers="{ 'Authorization': token.token, 'id': addData.id }">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-button @click="dialogVisible = false, imageUrl = '', clearadddata()">取消</el-button>
                    <el-button type="primary"
                        @click="dialogname == '添加用户' ? adduser() : updatauser(), imageUrl = ''">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="displaydel" :title=dialogname width="500">
            <el-icon color="red">
                <WarningFilled />
            </el-icon>
            <span style="text-align: center;display:block;font-size: 17px;">是否确认删除该用户</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="displaydel = false, clearadddata()">否</el-button>
                    <el-button type="primary" @click="deluser()">是</el-button>
                </div>
            </template>
        </el-dialog>



        <!--layout控制组件展示顺序-->
        <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
            layout="jumper, prev, pager, next, sizes, total" :total="totalpage" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-card>
</template>

<style scoped>
.el-p {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.form-inline .el-input {
    --el-input-width: 220px;
}

.form-inline .el-select {
    --el-select-width: 220px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    margin-inline-end: 20px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>